package cn.chi.user.controller;

import cn.chi.org.domain.Employee;
import cn.chi.org.mapper.EmployeeMapper;
import cn.chi.user.domain.LoginInfo;
import cn.chi.user.domain.User;
import cn.chi.user.mapper.LoginInfoMapper;
import cn.chi.user.service.impl.LogininfoServiceImpl;
import cn.chi.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private LogininfoServiceImpl logininfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmployeeMapper employeeMapper;
    @PostMapping("/user")
    public AjaxResult login(@RequestBody User user){
        System.out.println(user);
        try {
            //获取当前的登录用户信息
            LoginInfo loginInfo= logininfoService.login(user);
            //生成token
            String token = UUID.randomUUID().toString();
            //把当前用户和token 放到redis里面  并设置有效期是30分钟
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);
            System.out.println(loginInfo);
            //把 token  登录用户 返回给前端
            Map<String,Object> map = new HashMap();
            map.put("TOKEN",token);
            //返回给前端以前 清空敏感数据
            loginInfo.setPassword(null);
            loginInfo.setSalt(null);

            map.put("loginInfo",loginInfo);
            return AjaxResult.me().setResultObj(map);
        } catch (RuntimeException e) {
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }

    /**
     * 后台用户登录
     * @param employee
     * @return
     */
    @PostMapping("/emp")
    public AjaxResult loginEmp(@RequestBody Employee employee){
        System.out.println(employee);
        try {
            //获取用户信息
            LoginInfo loginInfo = logininfoService.loginemp(employee);
            System.out.println(loginInfo);
            //生成token
            String token = UUID.randomUUID().toString();
            //把当前的token和用户信息存到redis里
            redisTemplate.opsForValue().set(token, loginInfo,30,TimeUnit.MINUTES);
            //把token和用户返回给前段
            Map<String,Object> map = new HashMap();
            map.put("TOKEN",token);
            //清空用户的关键信息
            loginInfo.setPassword(null);
            loginInfo.setSalt(null);
            map.put("logIninfo",loginInfo);
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }
    }
}
